//
//  CollectionViewController.swift
//  DiffableDataSource
//
//  Created by bin hu on 2025/6/3.
//

import UIKit

class CollectionViewController: UIViewController {
    
    private var dataSource: UICollectionViewDiffableDataSource<CustomSection, CustomItem>!
    private var collectionView: UICollectionView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        setupCollectionView()
        configureDataSource()
        applyInitialSnapshot()
        navigationController?.navigationBar.prefersLargeTitles = true
    }
    
    func setupCollectionView() {
        // 1. 创建组合式布局
        let layout = UICollectionViewCompositionalLayout { [weak self] sectionIndex, _ in
            return self?.createLayout(for: sectionIndex)
        }
        // 2. 初始化 CollectionView
        collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout)
        collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        view.addSubview(collectionView)
        collectionView.showsVerticalScrollIndicator = false
        collectionView.contentInsetAdjustmentBehavior = .never
        //注册cell
        registerCell()
        // 4. 设置数据源（示例代码）
        collectionView.delegate  = self
        collectionView.dataSource = dataSource
        collectionView.alwaysBounceVertical = true
    }
    
    // MARK: - 核心布局配置
    private func createLayout(for section: Int) -> NSCollectionLayoutSection {
        switch section {
        case 0:
            return createListLayoutSection(100.0)
        case 1:
            return createGridLayoutSection(rate: 1/4, height: 110,itemContentInsets:.zero,sectionContentInsets: .zero)
        case 2:
            return createListLayoutSection(100.0)
        default:
            return createListLayoutSection(0)
        }
    }
    
    func registerCell()  {
        // 3. 注册 Cell
        collectionView.register(VerCollectionViewCell.self,forCellWithReuseIdentifier: NSStringFromClass(VerCollectionViewCell.self))
        collectionView.register(HorCollectionViewCell.self, forCellWithReuseIdentifier: NSStringFromClass(HorCollectionViewCell.self))
    }
    
    private func configureDataSource() {
        dataSource = UICollectionViewDiffableDataSource(collectionView: collectionView) {
            collectionView, indexPath, item in
            guard let section = CustomSection.allCases[safe: indexPath.section] else {
                return UICollectionViewCell()
            }
            if section.self == .vegetables {
                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(HorCollectionViewCell.self), for: indexPath)
                /// cell set data
                return cell
            }else{
                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(VerCollectionViewCell.self), for: indexPath)
                /// cell set data
                return cell
            }
            
        }
    }
    
    /// 实际情况是 网络请求后 在这里重配数据
    private func applyInitialSnapshot() {
        var snapshot = NSDiffableDataSourceSnapshot<CustomSection, CustomItem>()
        snapshot.appendSections(CustomSection.allCases)
        
        for section in CustomSection.allCases {
            snapshot.appendItems(section.items, toSection: section)
        }
        
        dataSource.apply(snapshot, animatingDifferences: false)
    }

}

extension CollectionViewController:UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
    }
    
}

//extension CollectionViewController:UICollectionViewDataSource {
//    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//        
//    }
//    
//    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//        
//    }
//}


///
struct CollectionCellConfiguration {
    var cellClass = UICollectionViewCell.self
}

/** iOS13以上使用 */
/// 列表布局
public func createListLayoutSection(_ height:CGFloat,
                                     hasHeader:Bool = false,
                                     headerHeight:CGFloat = 0.0,
                                     hasFooter:Bool = false,
                                     footerHeight:CGFloat = 0.0) -> NSCollectionLayoutSection {
    let itemSize = NSCollectionLayoutSize(
        widthDimension: .fractionalWidth(1.0),
        heightDimension: .absolute(height)
    )
    let item = NSCollectionLayoutItem(layoutSize: itemSize)
    
    let group = NSCollectionLayoutGroup.vertical(
        layoutSize: itemSize,
        subitems: [item]
    )
    let section = NSCollectionLayoutSection(group: group)
    section.interGroupSpacing = 8
    section.contentInsets = .zero
    if hasHeader {
        /// section头部
        let headerSize = NSCollectionLayoutSize(
            widthDimension: .fractionalWidth(1.0), // 宽度占满容器
            heightDimension: .absolute(headerHeight)         // 固定高度
        )
        let header = NSCollectionLayoutBoundarySupplementaryItem(
            layoutSize: headerSize,
            elementKind: UICollectionView.elementKindSectionHeader, // 类型标识
            alignment: .top // 布局位置（顶部对齐）
        )
        section.boundarySupplementaryItems.append(header)
    }
    if hasFooter {
        /// 创建footer布局项
        let footerSize = NSCollectionLayoutSize(
            widthDimension: .fractionalWidth(1.0),
            heightDimension: .absolute(footerHeight)
        )
        let footer = NSCollectionLayoutBoundarySupplementaryItem(
            layoutSize: footerSize,
            elementKind: UICollectionView.elementKindSectionFooter,
            alignment: .bottom
        )
        section.boundarySupplementaryItems.append(footer)
    }
    return section
}

// 网格布局（4列 rate = 0.25） 用configuration是不是好一点
public func createGridLayoutSection(rate:CGFloat,
                                    height:CGFloat,
                                    itemContentInsets:NSDirectionalEdgeInsets = NSDirectionalEdgeInsets(top: 4, leading: 4, bottom: 4, trailing: 4),
                                    sectionContentInsets:NSDirectionalEdgeInsets = NSDirectionalEdgeInsets(top: 16.0, leading: 8, bottom: 16, trailing: 8),
                                    is_horizontal_continuous:Bool = false,
                                    hasHeader:Bool = false,
                                    headerHeight:CGFloat = 0.0,
                                    hasFooter:Bool = false,
                                    footerHeight:CGFloat = 0.0) -> NSCollectionLayoutSection {
    let itemSize = NSCollectionLayoutSize(
        widthDimension: .fractionalWidth(rate),
        heightDimension: .fractionalHeight(1.0)
    )
    let item = NSCollectionLayoutItem(layoutSize: itemSize)
    item.contentInsets = itemContentInsets
    
    let groupSize = NSCollectionLayoutSize(
        widthDimension: .fractionalWidth(1.0),
        heightDimension: .absolute(height)
    )
    let group = NSCollectionLayoutGroup.horizontal(
        layoutSize: groupSize,
        subitems: [item]
    )
    
    let section = NSCollectionLayoutSection(group: group)
    section.contentInsets = sectionContentInsets
    section.orthogonalScrollingBehavior = is_horizontal_continuous ? .continuous : .none // 连续滚动
    if hasHeader {
        /// section头部
        let headerSize = NSCollectionLayoutSize(
            widthDimension: .fractionalWidth(1.0), // 宽度占满容器
            heightDimension: .absolute(headerHeight)         // 固定高度
        )
        let header = NSCollectionLayoutBoundarySupplementaryItem(
            layoutSize: headerSize,
            elementKind: UICollectionView.elementKindSectionHeader, // 类型标识
            alignment: .top // 布局位置（顶部对齐）
        )
        section.boundarySupplementaryItems.append(header)
    }
    if hasFooter {
        /// 创建footer布局项
        let footerSize = NSCollectionLayoutSize(
            widthDimension: .fractionalWidth(1.0),
            heightDimension: .absolute(footerHeight)
        )
        let footer = NSCollectionLayoutBoundarySupplementaryItem(
            layoutSize: footerSize,
            elementKind: UICollectionView.elementKindSectionFooter,
            alignment: .bottom
        )
        section.boundarySupplementaryItems.append(footer)
    }
    return section
}
